<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ErrorCode;
use App\Request\FormRequest;
use App\Utils\Other\Jwt\Token;
use Hyperf\Context\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function Hyperf\Translation\__;
use function Hyperf\Config\config;

class Authorization implements MiddlewareInterface
{

    public function __construct(
        protected ContainerInterface $container,
        protected Token $token,
        protected FormRequest $formRequest
    )
    { }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr7ResponseInterface
    {
        $token = getAuthorization();
        if (!$token) {
            return failed(__('message.jwt.failure'), ErrorCode::SERVER_UNAUTHORIZED);
        }

        $data = $this->token->decode($token, $newToken);

        $app = $this->formRequest->appName();

        Context::set("{$app}Info", $data);

        if ($newToken) {
            $response = Context::get(Psr7ResponseInterface::class);
            logs(config('jwt.prefix')." {$newToken}", 'new Authorization');
            $response = $response->withHeader('authorization', config('jwt.prefix')." {$newToken}");
            Context::set(Psr7ResponseInterface::class, $response);
        }

        return $handler->handle($request);
    }
}
